﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IRCBot.Messages;

namespace IRCBot.Modules
{
    public class GeneralModule : IModule
    {
        public event SendDataEvent SendData;
        public event SayEvent Say;
        public event DelayedSayEvent DelayedSay;
        public event ModuleEvent ClearDelayedMessages;

        public void HandleIncomingMessage(IncomingMessage message)
        {
            switch (message.Command.ToLower())
            {
                case ":!join":
                    HandleJoinChannel(message);
                    break;
                case ":!say":
                    HandleSay(message);
                    break;                
                case ":!part":
                    HandlePart(message);
                    break;
            }
        }
        
        private void HandleJoinChannel(IncomingMessage message)
        {
            try
            {
                string channelToJoin = message.GetParameterNumber(0);
                if (string.IsNullOrEmpty(channelToJoin))
                    Say("Invalid usage. Example: !join #channelName", message.Channel);
                else
                    SendData(new OutgoingMessage(CommandType.JOIN, channelToJoin));
            }
            catch (Exception ex)
            {
                throw new Exception("HandleJoinChannel: " + message.ToString());
            }
        }

        private void HandleSay(IncomingMessage message)
        {
            try
            {
                string channel = message.GetParameterNumber(0);
                string text = message.GetParametersFromIndex(1);

                if (string.IsNullOrEmpty(channel)||string.IsNullOrEmpty(text))
                    Say("Invalid usage. Example: !say #channel something", message.Channel);
                else
                    Say(text, channel);
            }
            catch (Exception ex)
            {
                throw new Exception("HandleSay: " + message.ToString());
            }
        }

        private void HandlePart(IncomingMessage message)
        {
            try
            {
                SendData(new OutgoingMessage(CommandType.PART, message.Channel));
            }
            catch (Exception ex)
            {
                throw new Exception("HandlePart: " + message.ToString());
            }
        }
    }
}
